import React, { Component } from 'react'
import MyNavBar from '../../components/MyNavBar'

import { getCityList, getHotCityList } from '../../api/city'
import { getCurrentCity, setLocalCity } from '../../utils/city'
import { AutoSizer, List } from 'react-virtualized'
import { Toast } from 'antd-mobile'

import styles from './index.module.scss'

const TITLE_HEIGHT = 36
const CITY_HEIGHT = 50
const HASDATA = ['北京', '上海', '广州', '深圳']

export default class CityList extends Component {
  constructor () {
    super()

    this.state = {
      cityListObj: null, // 左边的城市列表对象
      cityIndexList: null, // 右边的城市索引数组
      selectedIndex: 0 // 选中的索引
    }
  }

  // 切换城市的渲染
  toggleCitySelect = ({ label, value }) => {
    if (!HASDATA.includes(label)) {
      Toast.info('该城市暂无房源~', 1)
      return
    }

    // 保存到本地
    setLocalCity({ label, value })

    // 关闭当前页面
    this.props.history.goBack()
  }

  listRef = React.createRef()

  componentDidMount () {
    this.dealWithCityListData()
  }

  dealWithCityListData = async () => {
    // 处理a-z的数据
    const res1 = await getCityList()

    const tempObj = {}
    let tempIndexList = []
    res1.data.body.forEach(item => {
      // 把遍历到的那项的首字母取出来
      const letter = item.short.substr(0, 1)

      // 判断该字母的属性是否在tempObj中有值
      if (tempObj[letter]) {
        tempObj[letter].push(item)
      } else {
        tempObj[letter] = [item]
      }
    })

    tempIndexList = Object.keys(tempObj).sort()

    // 处理热门城市数据
    const res2 = await getHotCityList()
    tempObj['hot'] = res2.data.body
    tempIndexList.unshift('hot')

    // 处理定位城市
    const res3 = await getCurrentCity()
    tempObj['#'] = [res3]
    tempIndexList.unshift('#')

    this.setState({
      cityListObj: tempObj,
      cityIndexList: tempIndexList
    })
  }

  // 格式化标题
  formatTitle = letter => {
    switch (letter) {
      case '#':
        return '定位城市'

      case 'hot':
        return '热门城市'

      default:
        return letter.toUpperCase()
    }
  }

  // 切换右边的索引
  toggleSelect = index => {
    // console.log(index)
    // this.setState({
    //   selectedIndex: index
    // })
    this.listRef.current.scrollToRow(index)
  }

  rowRenderer = ({
    key, // Unique key within array of rows
    index, // Index of row within collection
    isScrolling, // The List is currently being scrolled
    isVisible, // This row is visible within the List (eg it is not an overscanned row)
    style // Style object to be applied to row (to position it)
  }) => {
    const { cityListObj, cityIndexList } = this.state
    const letter = cityIndexList[index]
    const list = cityListObj[letter]
    return (
      <div className={styles.city} style={style} key={key}>
        <div className={styles.title}>{this.formatTitle(letter)}</div>
        {list.map(item => {
          return (
            <div
              onClick={() => this.toggleCitySelect(item)}
              key={item.value}
              className={styles.name}
            >
              {item.label}
            </div>
          )
        })}
      </div>
    )
  }

  calcRowHeight = ({ index }) => {
    const { cityIndexList, cityListObj } = this.state
    const letter = cityIndexList[index]
    const list = cityListObj[letter]

    return TITLE_HEIGHT + list.length * CITY_HEIGHT
  }

  renderCityIndexList = () => {
    const { cityIndexList, selectedIndex } = this.state
    return (
      <div className={styles.cityIndex}>
        {cityIndexList.map((item, index) => {
          return (
            <div
              onClick={() => this.toggleSelect(index)}
              className={styles.cityIndexItem}
              key={item}
            >
              <span
                className={selectedIndex === index ? styles.indexActive : ''}
              >
                {item === 'hot' ? '热' : item.toUpperCase()}
              </span>
            </div>
          )
        })}
      </div>
    )
  }

  onRowsRendered = ({ startIndex }) => {
    if (startIndex !== this.state.selectedIndex) {
      this.setState({
        selectedIndex: startIndex
      })
    }
  }

  render () {
    const { cityIndexList } = this.state
    return (
      <div className={styles.citylist}>
        {/* <MyNavBar history={this.props.history}>城市选择</MyNavBar> */}
        <MyNavBar>城市选择</MyNavBar>
        {/* 渲染左边的列表 */}
        {cityIndexList && (
          <AutoSizer>
            {({ height, width }) => (
              <List
                ref={this.listRef}
                width={width}
                height={height - 45}
                rowCount={cityIndexList.length}
                rowHeight={this.calcRowHeight}
                rowRenderer={this.rowRenderer}
                onRowsRendered={this.onRowsRendered}
                scrollToAlignment='start'
              />
            )}
          </AutoSizer>
        )}
        {/* 渲染右边的索引 */}
        {cityIndexList && this.renderCityIndexList()}
      </div>
    )
  }
}
